import os
import time
import glob
import requests
import json
from logger import log
from settings import settings


def format_date_time(date_string):
    """格式化日期时间字符串 (YYMMDD-HHMMSS -> YYYY-MM-DD HH:MM:SS)"""
    return f"20{date_string[:2]}-{date_string[2:4]}-{date_string[4:6]} {date_string[7:9]}:{date_string[9:11]}:{date_string[11:13]}"


def post2(data_str):
    """处理文件内容并发送到服务器"""
    lines = data_str.strip().split('\n')

    # 解析文件内容
    nodes = []
    total_weight = 0.0
    total_max_weight = 0.0

    train_code = lines[3].split(":")[1].strip()
    total_nodes = int(lines[2].split(":")[1])

    for i in range(5, min(5 + total_nodes, len(lines))):
        data = [item.strip() for item in lines[i].split(',')]
        if len(data) < 12:
            continue

        weight = float(data[4]) if data[4] else 0.0
        max_weight = float(data[8]) if data[8] else 0.0

        total_weight += weight
        total_max_weight += max_weight

        node = {
            "diffWeight": float(data[9]) if data[9] else 0.0,
            "code": f"{train_code}-{data[1]}",
            "lable": None,
            "maxNetWeight": max_weight,
            "no": data[1],
            "sort": int(data[0]),
            "speed": 0.0,
            "standardTareWeight": float(data[3]) if data[3] else 0.0,
            "time": None,
            "trainCode": train_code,
            "carType": data[11],
            "weight": weight,
            "containerNumber1": None,
            "containerNumber2": None,
            "containerType1": None,
            "containerType2": None,
            "state": "Done",
            "frontBackDiff": None,
            "centerDeviation": None,
            "createTenantId": None,
            "createTenantName": None
        }
        nodes.append(node)

    # 构建列车数据
    train_co = {
        "boxCount": 0,
        "code": train_code,
        "deviceName": settings.name,
        "direction": "Leave" if lines[1].split(":")[1].strip() == "-->" else "Enter",
        "endTime": None,
        "firstNo": nodes[0]["no"] if nodes else None,
        "lastNo": nodes[-1]["no"] if nodes else None,
        "name": train_code,
        "no": train_code,
        "nodes": nodes,
        "platformId": settings.platformId,
        "platformName": settings.platformName,
        "productName": None,
        "senderName": lines[0],
        "startTime": None,
        "stationName": None,
        "time": format_date_time(train_code),
        "totalDiffWeight": total_weight - total_max_weight,
        "totalMaxWeight": total_max_weight,
        "totalNode": total_nodes,
        "totalWeight": total_weight,
        "type": "txt",
        "wagonType": None,
        "createTenantId": None,
        "createTenantName": None
    }

    # 发送数据到服务器
    try:
        headers = {'Content-Type': 'application/json'}
        response = requests.post(
            settings.server_url,
            data=json.dumps(train_co),
            headers=headers,
            timeout=10
        )
        log.info(f"发送成功: {response.status_code}")
    except Exception as e:
        log.error(f"发送失败: {str(e)}")


def get_latest_txt_files():
    """获取目录中最新的3个txt文件"""
    files = glob.glob(os.path.join(settings.directory, '*.txt'))
    # 使用绝对路径模式
    # pattern = os.path.join(settings.directory, '*.txt')
    # 使用绝对路径匹配
    # files = glob.glob(os.path.abspath(pattern))
    # 按修改时间排序（最新在前）
    files.sort(key=os.path.getmtime, reverse=True)
    return files[:3]


def collection():
    """采集并处理文件"""
    log.info("延时时间到，开始新的采集")
    try:
        latest_files = get_latest_txt_files()
        for file_path in latest_files:
            log.info(f"处理文件: {file_path}")
            try:
                # 使用GBK编码读取文件
                with open(file_path, 'r', encoding='gbk', errors='ignore') as f:
                    content = f.read()
                    post2(content)
            except Exception as e:
                log.error(f"处理文件出错 {file_path}: {str(e)}")
        else:
            log.info("所有文件处理完毕")
    except Exception as e:
        log.exception(e)
        log.error(f"采集出错: {str(e)}")


def main():
    """主函数"""
    log.info("开始运行")
    while True:
        collection()
        time.sleep(300)


if __name__ == "__main__":
    settings.init(local=True)
    main()
